package com.epfresh.supplier.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.epfresh.api.entity.RequestEntitySupply;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.global.BaseActivity;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.T;
import com.epfresh.supplier.R;
import com.epfresh.supplier.constant.Constant;
import com.epfresh.supplier.dialog.KnowDialog;
import com.epfresh.supplier.entity.OrderDetailAgent;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.epfresh.supplier.adapter.*;

import multitype.MultiTypeAdapter;
import multitype.OnRecyclerViewItemClickListener;

import com.epfresh.api.universalimageloader.core.*;
public class OrderDetailAgentActivity extends BaseActivity {

    TextView tv_order_detail_hope_date, tv_order_detail_agent_go, tv_order_detail_agent_id, tv_order_detail_agent_code,tv_order_detail_agent_base_title;
    View iv_order_detail_agent_phone,tv_order_detail_agent_store_go;
    View ll_order_detail_agent_code;

    RecyclerView rv_order_detail_agent_state;

    ImageView iv_order_detail_agent_product;
    TextView tv_order_detail_agent_product_title, tv_order_detail_agent_product_price, tv_order_detail_agent_product_size_detail,tv_order_detail_agent_goods_logistics;

    TextView tvMore;
    View vLineMore;
    private RecyclerView rv;

    TextView tv_order_detail_agent_money_percent,tv_order_detail_agent_money_all;
    View tv_order_detail_agent_money_percent_title;

    View rl_order_detail_agent_return;
    TextView tv_order_detail_agent_return;

    TextView tv_order_detail_agent_part, tv_order_detail_receiver,tv_order_detail_phone,tv_order_detail_address;
    View ll_order_detail_agent_receiver_info;


    View rl_order_detail_agent_parent_order,rl_product;
    TextView tv_item_order_parent_id,tv_item_order_parent_time,tv_item_order_parent_title,tv_item_order_parent_money;
    ImageView iv_order_detail_agent_pay;




    String id;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        id = getIntent().getStringExtra("id");
        if(id!=null){
            requestOrderInfo();
        }else {
            T.toast("没收到订单号");
            finish();
        }
    }

    private List<OrderDetailAgent.ContentBean.OrderListBean> mChildItems = new ArrayList<>();
    private List<OrderDetailAgent.ContentBean.OrderListBean> itemTow = new ArrayList<>();
    private MultiTypeAdapter mChildOrderAdapter;
    private OrderChildViewBinder orderChildViewBinder;
    void initList() {
        rv = (RecyclerView)findViewById(R.id.rv);
        tvMore = (TextView)findViewById(R.id.tv_more);
        vLineMore = findViewById(R.id.v_line_more);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        layoutManager.setAutoMeasureEnabled(true);


        rv.setLayoutManager(layoutManager);
        rv.setNestedScrollingEnabled(false);

        mChildOrderAdapter = new MultiTypeAdapter();
        orderChildViewBinder = new OrderChildViewBinder();
        orderChildViewBinder.setOnRecyclerViewItemClickListener(new OnRecyclerViewItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Object data) {
                if(!"10".equals(((OrderDetailAgent.ContentBean.OrderListBean)data).getJmtStatus())) {
                    Intent code = new Intent(mContext, OrderEnsureActivity.class);
                    code.putExtra("id", ((OrderDetailAgent.ContentBean.OrderListBean) data).getId());
                    code.putExtra("agentFlag", true);
                    startActivityForResult(code, 0x002);
                }else{
                    final KnowDialog dialog = new KnowDialog(mContext);
/*                    dialog.setCanceledOnTouchOutside(false);
                    dialog.setCancelable(false);*/
                    dialog.setOnSureListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            dialog.dismiss();
                        }
                    });
                    dialog.show();
                    //T.toast("有退款在申请中，暂时无法验证交货码");
                }
            }
        });
        mChildOrderAdapter.register(OrderDetailAgent.ContentBean.OrderListBean.class, orderChildViewBinder);
        rv.setAdapter(mChildOrderAdapter);
        mChildOrderAdapter.setItems(mChildItems);
        tvMore.setOnClickListener(this);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 0x002 && requestCode == 0x002) {
            requestOrderInfo();
        }
    }



    OrderStateViewBinder binder;
    MultiTypeAdapter mStateAdapter = new MultiTypeAdapter();
    List<Object> mStateItems = new ArrayList<>();

    void initView(){
        tvBack.setVisibility(View.VISIBLE);
        setContentView(R.layout.activity_order_detail_agent);

        rl_product = findViewById(R.id.rl_product);
        rl_product.setOnClickListener(this);
        rv_order_detail_agent_state = (RecyclerView)findViewById(R.id.rv_order_detail_agent_state);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_order_detail_agent_state.setLayoutManager(layoutManager);
        binder = new OrderStateViewBinder();
        mStateAdapter.register(OrderDetailAgent.ContentBean.StageStatusListBean.class, binder);
        rv_order_detail_agent_state.setAdapter(mStateAdapter);
        mStateAdapter.setItems(mStateItems);


        tv_order_detail_hope_date = (TextView) findViewById(R.id.tv_order_detail_group_state);
        tv_order_detail_agent_go = (TextView)findViewById(R.id.tv_order_detail_agent_go);
        tv_order_detail_agent_id = (TextView)findViewById(R.id.tv_order_detail_agent_id);
        tv_order_detail_agent_base_title = (TextView)findViewById(R.id.tv_order_detail_agent_base_title);
        tv_order_detail_agent_store_go = findViewById(R.id.tv_order_detail_agent_store_go);
        tv_order_detail_agent_store_go.setOnClickListener(this);
        iv_order_detail_agent_phone = findViewById(R.id.iv_order_detail_agent_phone);
        iv_order_detail_agent_phone.setOnClickListener(this);


        ll_order_detail_agent_code = findViewById(R.id.ll_order_detail_agent_code);
        tv_order_detail_agent_code = (TextView)findViewById(R.id.tv_order_detail_agent_code);

        tv_order_detail_agent_product_title = (TextView)findViewById(R.id.tv_order_detail_agent_product_title);
        tv_order_detail_agent_product_price = (TextView)findViewById(R.id.tv_order_detail_agent_product_price);
        tv_order_detail_agent_goods_logistics = (TextView)findViewById(R.id.tv_order_detail_agent_goods_logistics);
        tv_order_detail_agent_product_size_detail = (TextView)findViewById(R.id.tv_order_detail_agent_product_size_detail);
        iv_order_detail_agent_product = (ImageView)findViewById(R.id.iv_order_detail_agent_product);

        tv_order_detail_agent_money_percent = (TextView)findViewById(R.id.tv_order_detail_agent_money_percent);
        tv_order_detail_agent_money_percent_title = findViewById(R.id.tv_order_detail_agent_money_percent_title);
        tv_order_detail_agent_money_all = (TextView)findViewById(R.id.tv_order_detail_agent_money_all);

        tv_order_detail_agent_return = (TextView)findViewById(R.id.tv_order_detail_agent_return);
        rl_order_detail_agent_return = findViewById(R.id.rl_order_detail_agent_return);


        tv_order_detail_agent_part = (TextView)findViewById(R.id.tv_order_detail_agent_part);
        tv_order_detail_receiver = (TextView)findViewById(R.id.tv_order_detail_receiver);
        tv_order_detail_phone = (TextView)findViewById(R.id.tv_order_detail_phone);
        tv_order_detail_phone.setOnClickListener(this);
        tv_order_detail_address = (TextView)findViewById(R.id.tv_order_detail_address);

        ll_order_detail_agent_receiver_info = findViewById(R.id.ll_order_detail_agent_receiver_info);

        rightbtn.setOnClickListener(this);
        rightbtn.setText("帮助");
        rightbtn.setVisibility(View.VISIBLE);
        toolbarTitle.setText("代办订单详情");
        initList();

        rl_order_detail_agent_parent_order = findViewById(R.id.rl_order_detail_agent_parent_order);
        tv_item_order_parent_id = (TextView)findViewById(R.id.tv_item_order_parent_id);
        tv_item_order_parent_time = (TextView)findViewById(R.id.tv_item_order_parent_time);
        tv_item_order_parent_money = (TextView)findViewById(R.id.tv_item_order_parent_money);
        tv_item_order_parent_title = (TextView)findViewById(R.id.tv_item_order_parent_title);
        iv_order_detail_agent_pay = (ImageView) findViewById(R.id.iv_order_detail_agent_pay);


    }
    boolean openMore;

    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.rl_product:
                intent = new Intent(this, BaseProductDetailActivity.class);
                intent.putExtra("baseStoreId", data.getContent().getBaseStoreId());
                intent.putExtra("productId", data.getContent().getProductId());
                startActivity(intent);
                break;
            case R.id.iv_order_detail_agent_phone:
                intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + data.getContent().getBaseManagerPhone()));//调出来拨打页面；
                startActivity(intent);
                break;
            case R.id.tv_order_detail_agent_store_go:
                intent = new Intent(this, BaseStoreInfoActivity.class);
                intent.putExtra("baseStoreId", data.getContent().getBaseStoreId());
                startActivity(intent);
                break;
            case R.id.baseback:
                // 返回上一页
                finish();
                break;
            case R.id.rightbtn:
                intent = new Intent(this, WebActivity.class);
                intent.putExtra(Constant.KEY_WEB_URL, com.epfresh.api.constant.Constant.URL_HELP_AGENT_NOTICE);
                intent.putExtra(Constant.KEY_WEB_TITLE, getString(R.string.help));
                startActivity(intent);
                break;
            case R.id.tv_more:
                if (openMore) {
                    Drawable nav_up = getResources().getDrawable(R.mipmap.arrow_agent_down);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    tvMore.setCompoundDrawables(null, null, nav_up, null);
                    mChildOrderAdapter.setItems(itemTow);
                    tvMore.setText("更多");
                } else {
                    Drawable nav_up = getResources().getDrawable(R.mipmap.arrow_agent_up);
                    nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
                    tvMore.setCompoundDrawables(null, null, nav_up, null);
                    mChildOrderAdapter.setItems(mChildItems);
                    tvMore.setText("收起");
                }
                openMore = !openMore;
                mChildOrderAdapter.notifyDataSetChanged();
                break;
            case R.id.tv_order_detail_phone:
                intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + tv_order_detail_phone.getTag()));//调出来拨打页面；
                startActivity(intent);
                break;
            case R.id.tv_order_detail_agent_goods_logistics:
                intent = new Intent(this, OrderTrackActivity.class);
                intent.putExtra("grouponId", id);
                startActivity(intent);
                break;
        }
    }


    OnRequestListener<OrderDetailAgent> onRequestListener = new OnRequestListener<OrderDetailAgent>() {
        @Override
        public OrderDetailAgent jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, OrderDetailAgent.class);
        }

        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            showExceptionView(R.mipmap.upload_error, "服务器出现小错误，请稍后再试", HttpRequest.FAIL_NET_FAULT);
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            hideProgressDialog();
            showExceptionView(R.mipmap.upload_error, arg + "", HttpRequest.FAIL_NET_FAULT);
        }
        @Override
        public void onStart(Object tag) {
            showProgressDialog();
        }

        @Override
        public void onResponse(ResponseEntity<OrderDetailAgent> response, Object tag) {
            OrderDetailAgent responseElement = response.getResponseElement();
            updateOrderInfo(responseElement);
            hideProgressDialog();
        }
    };
    String cmdOrderDetails = "pm-order/baseorder/groupon/agencydetail";

    public void requestOrderInfo() {
        RequestEntitySupply<Map<String, String>> entity = new RequestEntitySupply<>();
        entity.setCmd(cmdOrderDetails);
        Map<String, String> map = new HashMap<>();
        map.put("grouponId",id);
        entity.setParameters(map);
        request(entity, cmdOrderDetails, onRequestListener);
    }
    OrderDetailAgent data;

    public void updateOrderInfo(OrderDetailAgent data) {
        this.data = data;
        OrderDetailAgent.ContentBean bean = data.getContent();
        if(bean.getGrouponStatus()==10||bean.getGrouponStatus()==20||bean.getGrouponStatus()==30||bean.getGrouponStatus()==40||bean.getGrouponStatus()==60){
            tv_order_detail_hope_date.setText("期望发货："+bean.getDeliverTime());
        }else if(bean.getGrouponStatus()==70||bean.getGrouponStatus()==80){
            tv_order_detail_hope_date.setText("到货日期："+bean.getEstimateArriveTime());
        }else{
            tv_order_detail_hope_date.setText("预计到货："+bean.getDeliverTime());
        }
        tv_order_detail_agent_base_title.setText(bean.getBaseStoreName());
        tv_order_detail_agent_go.setText("发往"+bean.getAgencyCityName()+"-"+bean.getAgencyMarketName());
        tv_order_detail_agent_id.setText("拼货单号："+bean.getNumber());
        if(bean.getInspectCode()==null){
            ll_order_detail_agent_code.setVisibility(View.GONE);
        }else{
            tv_order_detail_agent_code.setText(bean.getInspectCode());
            ll_order_detail_agent_code.setVisibility(View.VISIBLE);
        }
        mStateItems.addAll(bean.getStageStatusList());
        mStateAdapter.notifyDataSetChanged();
        if(bean.getStageStatusList()!=null&&bean.getStageStatusList().size()>5) {
            int position=0;
            for(int i=0;i<bean.getStageStatusList().size();i++){
                if(bean.getStageStatusList().get(i).isCurNode()){
                    position = i;
                    break;
                }
            }
            if(position>4)
                rv_order_detail_agent_state.scrollToPosition(position-2);
        }
        mChildItems.addAll(bean.getOrderList());
        mChildOrderAdapter.notifyDataSetChanged();
        ImageLoader.getInstance().displayImage(bean.getThumbnail(), iv_order_detail_agent_product);
        tv_order_detail_agent_product_title.setText(bean.getProductTitle());
        tv_order_detail_agent_product_price.setText("单价："+bean.getPriceUnitRange());
        tv_order_detail_agent_product_size_detail.setText("总集货量："+bean.getSumProductCount()+bean.getChargeUnit());
        tv_order_detail_agent_goods_logistics.setOnClickListener(this);

        tv_order_detail_agent_money_percent.setText(bean.getAgencySettleAmount()+"元("+bean.getAgencyExpenseRate()+"%)");
        tv_order_detail_agent_money_all.setText(bean.getSumReqProductPrice()+"元");
        if(bean.getAgencySettleStatus()==20||bean.getAgencySettleStatus()==30){
            tv_order_detail_agent_money_percent.setVisibility(View.VISIBLE);
            tv_order_detail_agent_money_percent_title.setVisibility(View.VISIBLE);
        }else {
            tv_order_detail_agent_money_percent.setVisibility(View.GONE);
            tv_order_detail_agent_money_percent_title.setVisibility(View.GONE);
        }

        if(bean.getSumRefund()==null||"0".equals(bean.getSumRefund())){
            rl_order_detail_agent_return.setVisibility(View.GONE);
        }else {
            rl_order_detail_agent_return.setVisibility(View.VISIBLE);
            tv_order_detail_agent_return.setText(bean.getSumRefund()+"元");
        }

        tv_order_detail_agent_part.setText("代办方："+bean.getAgencyStoreName());
        tv_order_detail_receiver.setText("收货人："+bean.getAgencyReceiveName());
        tv_order_detail_address.setText("配送地址："+bean.getAgencyReceiveAddress());
        tv_order_detail_phone.setText(bean.getAgencyReceivePhone());
        tv_order_detail_phone.setTag(bean.getAgencyReceivePhone());
        rl_order_detail_agent_parent_order.setVisibility(View.GONE);
        if(bean.getAgencySettleStatus()!=null) {
            if (bean.getAgencySettleStatus() == 20) {
                tv_item_order_parent_id.setText("结算单号："+bean.getAgencySettleNo());
                tv_item_order_parent_time.setText(bean.getSettleStartTime());
                tv_item_order_parent_money.setText(bean.getAgencySettleAmount() + "元");
                tv_item_order_parent_title.setText("未结算金额");
                iv_order_detail_agent_pay.setImageResource(R.mipmap.order_agent_unpay);
                rl_order_detail_agent_parent_order.setVisibility(View.VISIBLE);
            } else if (bean.getAgencySettleStatus() == 30) {

                tv_item_order_parent_id.setText("结算单号："+bean.getAgencySettleNo());
                tv_item_order_parent_time.setText(bean.getSettleStartTime());
                tv_item_order_parent_money.setText(bean.getAgencySettleAmount() + "元");
                tv_item_order_parent_title.setText("已结算金额");
                iv_order_detail_agent_pay.setImageResource(R.mipmap.order_agent_payed);

                rl_order_detail_agent_parent_order.setVisibility(View.VISIBLE);

                iv_order_detail_agent_pay.setImageResource(R.mipmap.order_agent_payed);
            }
        }
        mChildItems.clear();
        itemTow.clear();
        mChildItems.addAll(bean.getOrderList());
        Drawable nav_up = getResources().getDrawable(R.mipmap.arrow_agent_down);
        nav_up.setBounds(0, 0, nav_up.getMinimumWidth(), nav_up.getMinimumHeight());
        tvMore.setCompoundDrawables(null, null, nav_up, null);
        tvMore.setText("更多");
        if (bean.getOrderList().size() > 2) {
            vLineMore.setVisibility(View.VISIBLE);
            tvMore.setVisibility(View.VISIBLE);
            tvMore.setOnClickListener(this);
            itemTow = bean.getOrderList().subList(0, 2);
            mChildOrderAdapter.setItems(itemTow);
        } else {
            vLineMore.setVisibility(View.GONE);
            mChildOrderAdapter.setItems(mChildItems);
            tvMore.setVisibility(View.GONE);
        }
        orderChildViewBinder.packageUnit = bean.getChargeUnit();
        mChildOrderAdapter.notifyDataSetChanged();
    }
}
